package com.heima.article.listen;

import com.heima.common.constants.article.HotArticleConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
@Slf4j
public class HotArticleScoreListener {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

  @RabbitListener(
      queuesToDeclare = {@Queue(value = HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE)})
  public void articleBehaviorHandler(
          @Payload String articleMess, Message message, Channel channel) {
      log.info("行为发生变化，发送的消息，{}",articleMess);
      try {
      //将发布消息缓存到redis,队列中
      ListOperations<String, String> listOperations = redisTemplate.opsForList();
      listOperations.rightPush(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST,articleMess);
    //进行手动确认消息

          channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
          log.info("收到行为发送的消息，{}",articleMess);
      } catch (IOException e) {
          e.printStackTrace();

          log.error("收到行为发送的消息失败,消息{}，原因{}",articleMess,e.getMessage());
      }

  }
}
